package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQueryObject;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentMongoRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentMongoService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.io.StringReader;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentMongoServiceImpl implements IStrategyCommentMongoService{

    @Autowired
    private StrategyCommentMongoRepository repository;
    //注入MongoTemplate
    @Autowired
    private MongoTemplate template;

    @Override
    public void save(StrategyComment strategyComment) {
        //填充评论时间
        strategyComment.setCreateTime(new Date());
        repository.save(strategyComment);
    }

    public Page<StrategyComment> query(StrategyCommentQueryObject qo){
//        Query query = new Query();
//        query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
//
//        //查询记录数
//        long total = template.count(query, StrategyComment.class);
//        //查询集合
//        List<StrategyComment> list = template.find(query, StrategyComment.class);
//        return new PageImpl<>(list,PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize()));
        //因为mongodb分页是从0开始的所以这里需要减一

        return repository.findByDetailId(qo.getDetailId(), PageRequest.of(qo.getCurrentPage()-1,
                qo.getPageSize()));
    }
    //点赞功能 当前用户点赞
    public void commentThumbUp(String toId,Long fromId){
        //1.根据id查询评论对象
        Optional<StrategyComment> op = repository.findById(toId);
        op.ifPresent(comment ->{
            //2.获取当前评论点赞集合
            List<Long> thumbuplist = comment.getThumbuplist();
            //3.判断当前点赞列表中是否含有当前点击用户
            if(thumbuplist.contains(fromId)){
                //取消
                thumbuplist.remove(fromId);
            }else{
                thumbuplist.add(fromId);
            }
            //直接获取集合的长度 就能拿到点赞数
            comment.setThumbupnum(thumbuplist.size());
            //保存到mongodb中
            repository.save(comment);
        });
    }

}
